// pages/login/login.js
//引入request方法，获取token，获取用户信息
import {reqLogin,reqUserInfo} from '../../api/user'
//引入存入本地数据的方法
import {setStorage} from '../../utils/storage'
//引入提示框
import {} from '../../utils/extendApi'

//引入模块让page与仓库进行关联
import {ComponentWithStore} from 'mobx-miniprogram-bindings'
//引入仓库
import {useStore} from '../../store/userstore'
ComponentWithStore({
        storeBindings:{
          store:useStore,
          fields:['token','userInfo'],
          actions:['setToken','setUserInfo']
        },
  //点击登录逻辑
methods: {
  login(){
    wx.login({
      success: async (res) => {
        const {code} = res
        const userData = await reqLogin(code)
        if (userData.code ===200) {
          //将token存储到浏览器存储里
          setStorage("token",userData.data.token)
          //将token存储到本地仓库里
          this.setToken(userData.data.token)

          //获取用户信息
          this.getUserInfo()
          wx.navigateBack()
        }else {
          wx.modal({title:"提示",content:"授权错误，请重新登录",showCancel:false})
        }
        // console.log(userData);
      },
    })
  },
  async getUserInfo(){
      //调用接口，得到用户信息
      const userInfo = await reqUserInfo()
      //将数据存到本地
      setStorage("userInfo",userInfo.data)
      //将数据存储到store仓库
      this.setUserInfo(userInfo.data)
  }
},
})
